package com.atguigu.gmall.common.config.exception.component;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author lfy
 * @Description
 * @create 2023-07-25 14:10
 */
//@ResponseBody
//@ControllerAdvice  //收集Controller的所有异常
    @Slf4j
@RestControllerAdvice
public class AppGlobalExceptionHandler {


    /**
     * 所有的业务异常
     * @param exception
     * @return
     */
    @ExceptionHandler(GmallException.class)
    public Result handleException(GmallException exception){

        //1、构造业务错误状态码
        Result<Object> result = new Result<>();
        result.setCode(exception.getCode());
        result.setMessage(exception.getMessage());
        result.setOk(false);

        return result;
    }


    /**
     * 精确处理数据校验错误
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException exception){

        BindingResult result = exception.getBindingResult();

        String allMsg = "";
        //提取错误信息
        for (FieldError error : result.getFieldErrors()) {
            String field = error.getField(); //发生错误的字段名
            String message = error.getDefaultMessage();//拿到错误提示
            allMsg += field+"："+message+"；";
        }

        Result<Object> res = new Result<>();
        res.setCode(ResultCodeEnum.VALIDATED_FAILED.getCode());
        res.setMessage(allMsg);
        res.setOk(false);

        return res;
    }


    @ExceptionHandler(Throwable.class)
    public Result handleException02(Throwable throwable){

        //1、构造业务错误状态码
        ResultCodeEnum error = ResultCodeEnum.SERVICE_ERROR;

        Result<Object> result = new Result<>();
        String message = throwable.getMessage();
        result.setCode(error.getCode());
        result.setMessage(message);
        result.setOk(false);

        log.error("系统异常：{}",throwable);

        return result;
    }
}
